<?php
namespace app\admin\controller;

use think\Controller;
use think\Validate;
use app\common\model\Admin as AdminModel;

/**
 * 登录管理
 * @package app\admin\controller
 */
class Access extends Controller
{
    private $model = null;

    # 初始化模型
    public function _initialize()
    {
        if (is_null($this->model)) {
            $this->model = new AdminModel;
        }
    }
    # 登陆
    public function login()
    {
        if (request()->isAjax()) {
            $data=input('post.');
            $rules = [
                'username'=>'require',
                'password'=>'require',
            ];
            $message = [
                'username.require' => '用户名不能为空',
                'password.require' => '密码不能为空',
            ];
            $validate = new Validate($rules, $message);
            if (!$validate->check($data)) {
                return json(['errno'=>1,'msg'=>$validate->getError()]);
            }
            if (!$user = $this->model->checkUser($data['username'], $data['password'])) {
                return json(['errno'=>1, 'msg'=>'用户名或密码输入有误']);
            }
            $data=[
                'username'    =>  $user['username'],
                'nickname'    =>  $user['nickname'],
                'avatar'      =>  $user['avatar'],
                'login_ip'    =>  $loginfo['login_ip']=request()->ip(),
                'login_time'  =>  $loginfo['login_time']=request()->time(),
                'login_id'    =>  $loginfo['login_id']=createUuid(),
            ];
            $this->model->updateData($loginfo);
            session('admin', $data);
            return json(['errno'=>0,'msg'=>session('admin.username')]);
        } else {
            if (session('?admin')) {
                $this->redirect('admin/index/index');
            } else {
                return $this->fetch();
            }
        }
    }
    # 登出
    public function logout()
    {
        session('admin', null);
        $this->success('退出中', 'admin/access/login');
    }

    # 密码找回
    public function retrieve()
    {
        if (!request()->isAjax()) {
            $this->redirect('admin/access/login');
        }
        $data=input('post.');
        if (!captcha_check($data['captcha'])) {
            return json(['errno'=>1,'msg'=>'验证码错误']);
        }
        $mail=$this->model->getDataByWhere(['name'=>'email']);
        if ($mail!=$data['email']) {
            return json(['errno'=>1,'msg'=>'对不起，该邮箱未注册']);
        }
        $sendTime = date('Y-m-d H:i', request()->time());
        $newPassword=getRandPassword();
        $content=<<<php
<div style='background-color:#ccc;text-align:center;padding:40px;'>
    <div style='width:640px;margin:0 auto;padding:10px;color:#333;background-color:#fff;border:0px solid #aaa;border-radius:5px;-webkit-box-shadow:3px 3px 10px #999;-moz-box-shadow:3px 3px 10px #999;box-shadow:3px 3px 10px #999;font-family:Verdana, sans-serif;'>
        <p>尊敬的{$data['email']},您好!
            <br/></p>
        <p>您在{$sendTime}时发起找回密码的请求：</p>
        <p>系统已将你的站点登陆密码重置为：</p>
        <p style="text-align:center;margin:0 25px;border:1px solid #cccccc;padding:20px;">
                <strong>{$newPassword}</strong>
        </p>
        <p>
            <span style="color: rgb(255, 0, 0);">
                <strong>
                    <span style="text-align:center;font-size:15px;">请及时登陆网站，修改密码</span>
                </strong>
            </span>
        </p>
        <p>
            <small stylle="text-align:right;color:#333">以上内容为系统自动发出，请勿直接回复。谢谢</small></p>
    </div>
</div>
php;
        if (!$this->model->updateData(passwdSet($newPassword), ['name'=>'password'])) {
            return json(['errno'=>1,'msg'=>'对不起，由于系统原因无法更改密码，请稍后重试']);
        }
        $sendResult=sendMail($data['email'], '找回密码', $content);
        if (1===$sendResult['errno']) {
            return json(['errno'=>1,'msg'=>$sendResult['msg']]);
        }
        return json(['errno'=>0,'msg'=>'系统已经重置您的登录密码并发至您的邮箱，请及时登录修改密码']);
    }
}
